package eerbaar.v2.gamebuilder.client.request;

import java.io.ByteArrayInputStream;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;

import eerbaar.game.IGame;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.persist.ISerializerService;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.v2.app.GameHelper;
import eerbaar.v2.gamebuilder.Config;
import eerbaar.v2.gamebuilder.client.UserID;

public class RequestType {

    // private final static String url2 = "http://www.eerbaar.com/";
    private static String url2;
    private final static String userId = UserID.getInstance().toString();

    public static final RequestType GET_GAME = new RequestType("getGame");
    public static final RequestType NEXT_LEVEL = new RequestType("nextLevel");
    public static final RequestType RESET_GAME = new RequestType("resetGame");
    private final String text;
    private final String path;

    static {
        RequestType.url2 = Config.calcServer();
    }

    protected RequestType(String text) {
        this("game", text);
    }

    public RequestType(String path, String text) {
        this.text = text;
        this.path = path;
    }

    protected void assignGame(HttpPost method) {

        IGame game = GameHelper.getGame();
        if (game == null) {
            return;
        }

        try {
            ISerializerService service = ServiceFactory
                    .getService(ISerializerService.class);
            String data = service.save(IGame.class, game);

            BasicHttpEntity entity = new BasicHttpEntity();
            ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
            entity.setContent(in);
            method.setEntity(entity);

        } catch (GameException e) {
            e.printStackTrace();
        }

    }

    public HttpPost getHttpPost() {

        HttpPost method = new HttpPost(getUrl() + this.path);
        method.setHeader("action", getText());
        method.setHeader("key", getUserID());

        assignGame(method);
        return method;
    }

    public String getText() {
        return this.text;
    }

    public String getUrl() {

        return RequestType.url2;
    }

    public String getUserID() {
        return userId;
    }

}
